<template>
  <div class="wash-inventory">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="物品名称">
          <el-input v-model="searchForm.name" placeholder="请输入物品名称" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="化学品" value="chemical" />
            <el-option label="工具" value="tool" />
            <el-option label="耗材" value="consumable" />
            <el-option label="设备配件" value="equipment_part" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select v-model="searchForm.stockStatus" placeholder="请选择状态" clearable>
            <el-option label="库存充足" value="sufficient" />
            <el-option label="库存偏低" value="low" />
            <el-option label="库存不足" value="insufficient" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>库存管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加物品
          </el-button>
        </div>
      </template>
      
      <el-table :data="inventoryList" v-loading="loading" border>
        <el-table-column prop="name" label="物品名称" />
        <el-table-column prop="category" label="分类">
          <template #default="{ row }">
            {{ getCategoryText(row.category) }}
          </template>
        </el-table-column>
        <el-table-column prop="currentStock" label="当前库存" />
        <el-table-column prop="minStock" label="最低库存" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="unitPrice" label="单价">
          <template #default="{ row }">
            ¥{{ row.unitPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStockStatusType(row.currentStock, row.minStock)">
              {{ getStockStatusText(row.currentStock, row.minStock) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastUpdateTime" label="最后更新" width="160" />
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleInbound(row)">入库</el-button>
            <el-button type="text" @click="handleOutbound(row)">出库</el-button>
            <el-button type="text" @click="handleViewHistory(row)">记录</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 物品编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '添加物品' : '编辑物品'"
      width="600px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="物品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入物品名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%;">
            <el-option label="化学品" value="chemical" />
            <el-option label="工具" value="tool" />
            <el-option label="耗材" value="consumable" />
            <el-option label="设备配件" value="equipment_part" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前库存" prop="currentStock">
          <el-input-number v-model="formData.currentStock" :min="0" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="最低库存" prop="minStock">
          <el-input-number v-model="formData.minStock" :min="0" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="formData.unit" placeholder="如：个、瓶、桶等" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input-number v-model="formData.unitPrice" :min="0" :precision="2" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 出入库对话框 -->
    <el-dialog
      v-model="stockDialogVisible"
      :title="stockType === 'inbound' ? '入库操作' : '出库操作'"
      width="500px"
    >
      <el-form ref="stockFormRef" :model="stockForm" :rules="stockRules" label-width="100px">
        <el-form-item label="物品名称">
          <el-input :value="currentItem.name" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input :value="`${currentItem.currentStock} ${currentItem.unit}`" disabled />
        </el-form-item>
        <el-form-item :label="stockType === 'inbound' ? '入库数量' : '出库数量'" prop="quantity">
          <el-input-number v-model="stockForm.quantity" :min="1" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="操作原因" prop="reason">
          <el-input v-model="stockForm.reason" placeholder="请输入操作原因" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="stockForm.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="stockDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleStockSubmit" :loading="stockLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { inventory } from '@/api/wash/index'

const loading = ref(false)
const submitLoading = ref(false)
const stockLoading = ref(false)
const dialogVisible = ref(false)
const stockDialogVisible = ref(false)
const dialogType = ref('create')
const stockType = ref('inbound')
const formRef = ref()
const stockFormRef = ref()
const inventoryList = ref([])
const currentItem = ref({})

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  stockStatus: ''
})

// 分页
const page = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  category: '',
  currentStock: 0,
  minStock: 0,
  unit: '',
  unitPrice: 0,
  remark: ''
})

// 出入库表单
const stockForm = reactive({
  quantity: 1,
  reason: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入物品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  currentStock: [{ required: true, message: '请输入当前库存', trigger: 'blur' }],
  minStock: [{ required: true, message: '请输入最低库存', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  unitPrice: [{ required: true, message: '请输入单价', trigger: 'blur' }]
}

const stockRules = {
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入操作原因', trigger: 'blur' }]
}

const getInventoryList = async () => {
  loading.value = true
  try {
    const res = await inventory.list({
      page: page.current - 1,
      size: page.size,
      ...searchForm
    })
    if (res && res.data) {
      inventoryList.value = res.data.content || []
      page.total = res.data.totalElements || 0
    } else {
      inventoryList.value = []
      page.total = 0
    }
  } catch (error) {
    console.error('获取库存列表失败:', error)
    ElMessage.warning('获取库存列表失败，请检查网络连接')
    inventoryList.value = []
    page.total = 0
  } finally {
    loading.value = false
  }
}

const getCategoryText = (category) => {
  const categoryMap = {
    chemical: '化学品',
    tool: '工具',
    consumable: '耗材',
    equipment_part: '设备配件'
  }
  return categoryMap[category] || category
}

const getStockStatusType = (current, min) => {
  if (current <= min) return 'danger'
  if (current <= min * 1.5) return 'warning'
  return 'success'
}

const getStockStatusText = (current, min) => {
  if (current <= min) return '库存不足'
  if (current <= min * 1.5) return '库存偏低'
  return '库存充足'
}

const handleSearch = () => {
  page.current = 1
  getInventoryList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    category: '',
    stockStatus: ''
  })
  handleSearch()
}

const handleAdd = () => {
  dialogType.value = 'create'
  resetFormData()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleInbound = (row) => {
  currentItem.value = row
  stockType.value = 'inbound'
  resetStockForm()
  stockDialogVisible.value = true
}

const handleOutbound = (row) => {
  currentItem.value = row
  stockType.value = 'outbound'
  resetStockForm()
  stockDialogVisible.value = true
}

const handleViewHistory = (row) => {
  ElMessage.info('库存记录功能开发中')
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (dialogType.value === 'create') {
      await inventory.create(formData)
    } else {
      await inventory.update(formData.id, formData)
    }

    ElMessage.success(dialogType.value === 'create' ? '添加成功' : '更新成功')
    dialogVisible.value = false
    getInventoryList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleStockSubmit = async () => {
  try {
    await stockFormRef.value.validate()
    stockLoading.value = true
    
    const data = {
      itemId: currentItem.value.id,
      quantity: stockForm.quantity,
      reason: stockForm.reason,
      remark: stockForm.remark
    }
    
    if (stockType.value === 'inbound') {
      await inventory.updateStock(currentItem.value.id, {
        quantity: stockForm.quantity,
        type: 'inbound',
        reason: stockForm.reason,
        remark: stockForm.remark
      })
    } else {
      await inventory.updateStock(currentItem.value.id, {
        quantity: -stockForm.quantity,
        type: 'outbound',
        reason: stockForm.reason,
        remark: stockForm.remark
      })
    }

    ElMessage.success(`${stockType.value === 'inbound' ? '入库' : '出库'}成功`)
    stockDialogVisible.value = false
    getInventoryList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    stockLoading.value = false
  }
}

const resetFormData = () => {
  Object.assign(formData, {
    id: '',
    name: '',
    category: '',
    currentStock: 0,
    minStock: 0,
    unit: '',
    unitPrice: 0,
    remark: ''
  })
}

const resetStockForm = () => {
  Object.assign(stockForm, {
    quantity: 1,
    reason: '',
    remark: ''
  })
}

const handleSizeChange = () => {
  getInventoryList()
}

const handleCurrentChange = () => {
  getInventoryList()
}

onMounted(() => {
  getInventoryList()
})
</script>

<style lang="scss" scoped>
.wash-inventory {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style> 